package com.gz.furnitures.dao.impl;

import com.gz.furnitures.dao.BasicDao;
import com.gz.furnitures.dao.FurnDao;
import com.gz.furnitures.entity.Furn;

import java.util.Collections;
import java.util.List;

public class FurnDaoImpl extends BasicDao<Furn> implements FurnDao {
    @Override
    public List<Furn> queryFurns() {
        //注意这里img_path要改成别名imgPath(即entity Furn中的imgPath)，否则反射找不到
        String sql = "SELECT id, `name`, maker, price,sales,stock,img_path imgPath from furn;";
        return queryMulti(sql, Furn.class);
    }

    @Override
    public int addFurn(Furn furn) {
        String sql="insert into furn(id,`name`,maker,price,sales,stock,img_path) " +
                "values(null,?,?,?,?,?,?)";
        return update(sql,furn.getName(),furn.getMaker(),
                furn.getPrice(),furn.getSales(),furn.getStock(),furn.getImgPath());
    }

    @Override
    public int deleteFurnById(int Id) {
        String sql="delete from furn where id=?";
        return update(sql,Id);
    }

    @Override
    public Furn queryFurnById(int id) {
        String sql="select id, `name`, maker, price,sales,stock,img_path imgPath from furn where id=?";
        return querySingle(sql, Furn.class,id);
    }

    @Override
    public int updateFurn(Furn furn) {
        String sql="update furn set `name`=?,maker=?,price=?,sales=?,stock=?,img_path=? where id=?";
        //这里img_path在furn_update.jsp中没有设置，根据Furn对象，没有设置则为默认路径
        return update(sql,furn.getName(),furn.getMaker(),furn.getPrice(),
                furn.getSales(),furn.getStock(),furn.getImgPath(),furn.getId());
    }

    @Override
    public int getTotalRow() {
        String sql="select count(*) from furn";
        //注意，这里不能写成return (Integer)queryScalar(sql);
        // 他返回的不是Integer类型，会报cast异常
        return ((Number)queryScalar(sql)).intValue();
    }

    @Override
    //begin是从0 开始
    //pageSize表示取出多少条数据
    public List<Furn> getPageItems(int begin, int pageSize) {
        String sql="select id, `name`, maker, price,sales,stock,img_path imgPath from furn  limit ?,?";
        return queryMulti(sql,Furn.class,begin,pageSize);
    }

    @Override
    public int getTotalRowByName(String name) {
        //模糊查询
        String sql="select count(*) from furn where `name` LIKE ?";
        return ((Number)queryScalar(sql,"%"+name+"%")).intValue();
    }

    @Override
    public List<Furn> getPageItemsByName(int begin, int pageSize, String name) {
        String sql="select id, `name`, maker, price,sales,stock,img_path imgPath from furn where `name` LIKE ? limit ?,?";
        return queryMulti(sql,Furn.class,"%"+name+"%",begin,pageSize);
    }

}
